import React, { Component } from 'react';
import { Dialog, PrimaryButton } from 'office-ui-fabric-react';

import FieldEditor from './FieldEditor';
import FormPreviewer from './FormPreviewer';

const STORANGE_KEY = 'FORM_DESIGNER_FIELDS';

const saveFields = fields => {
  const fieldJson = JSON.stringify(fields);
  localStorage.setItem(STORANGE_KEY, fieldJson);
};

const getSavedFields = () => {
  const fieldJson = localStorage.getItem(STORANGE_KEY);
  let stroedFields;
  if (fieldJson) {
    try {
      stroedFields = JSON.parse(fieldJson);
    } catch {}
  }

  return stroedFields || [];
};

class FormDesigner extends Component {
  constructor(props) {
    super(props);
    this.state = { fields: getSavedFields(), fieldEditorHidden: true };
  }

  showFieldEditor = () => {
    this.setState({ fieldEditorHidden: false });
  };

  hideFieldEditor = () => {
    this.setState({ fieldEditorHidden: true });
  };

  addField = field => {
    this.setState(({ fields }) => {
      const newFields = fields
        .filter(item => item.name !== field.name)
        .concat([field]);
      saveFields(newFields);
      return { fields: newFields };
    });
  };

  removeField = dropFields => {
    this.setState(({ fields }) => {
      const newFields = fields.filter(item =>
        dropFields.every(field => field.name !== item.name)
      );
      saveFields(newFields);
      return { fields: newFields };
    });
  };

  render() {
    return (
      <div>
        <div style={{ marginBottom: '1em', textAlign: 'right' }}>
          <PrimaryButton onClick={this.showFieldEditor}>
            显示表单设计器
          </PrimaryButton>
        </div>
        <Dialog
          hidden={this.state.fieldEditorHidden}
          maxWidth={980}
          onDismiss={this.hideFieldEditor}
          dialogContentProps={{
            title: '表单设计器'
          }}
        >
          <FieldEditor
            fields={this.state.fields}
            onAddField={this.addField}
            onRemoveField={this.removeField}
          />
        </Dialog>

        <FormPreviewer fields={this.state.fields} />
      </div>
    );
  }
}

FormDesigner.propTypes = {};

export default FormDesigner;
